import requests
from lxml import etree
import re
import time

class playlist(object):
    def __init__(self, playlist_id):
        self.playlist_id = playlist_id

    def spider(self):
        time.sleep(0.5)
        url = 'https://music.163.com/playlist'
        headers = {
            "cookie": "_ntes_nnid=5c99ad045581e064fad769bab5315216,1609045511812; _ntes_nuid=5c99ad045581e064fad769bab5315216; NMTID=00OwWXDFshRyeoKY0FRufLJKpoNU-AAAAF2opYJaA; WM_TID=vZ85Qxp2ap9EQBUQVAJqOdwZ1jgU7CGI; ntes_kaola_ad=1; _iuqxldmzr_=32; __csrf=40362ea41bd4a5025b0ad43dbe2daa81; MUSIC_U=7b556cee10dece13cf2d554a70f574c56fa8e7110d97bedf8da5adb9834c824433a649814e309366; hb_MA-B407-E266474A0BB8_source=www.163yun.com; WM_NI=0GRxyR%2B%2B0fOGudhm5Flodb7qDB2bx6dWaDCPQdwNaJeihbr3dxnGXXXDqu9HHkCHr6GsArUtTl8O1%2BQm8SW9TWf1B1e%2FHd%2F%2FrKHiUABZTIsvNexLq%2FHX4DcujWz%2BQS%2BMdmc%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6eeb5bc539c928e8cbc6090a88ab2d14e869a9eaef16d98b7a3a3d36eb5ebbcade12af0fea7c3b92af4999e99fc5ae9f50087ce4db7bca88eb84eb0b1ac83b67b889efe83fb3ea889afa5c25c93bcb9afe442a7b7a883f139a8a8a2a8db549c9cbf96bc448cb58da9f13e85ad8f93d88098b4f8b0b42193b3f8b4d6339889aad2c13ba7f18885ae25b295888ad84b82869caaf27e8ebbb8adf4258c88fca5e27faa89b6ccd459e993ac8ee237e2a3; WEVNSM=1.0.0; WNMCID=vzmwiy.1616737327232.01.0; JSESSIONID-WYYY=m3KNiFwjlAVeBs%5CFjeA%2BD1Pk0i7rI%5CPeWXaM9nFIl4YTTgBsUcPQHwcWch9OIij6UYxzomdjDUTm0G5Ga68yslHsW8wGnV5kr2vnDiJ57WD3WuzZr4ECSPbGDqyn3%2FJn3oQ4%5CsGYji9uJ9YJG8CZMt0SafK%5C9NQFyRUZu%5CXe4dNbDO4N%3A1616746084368",
            "dnt": "1",
            "referer": "https://music.163.com/",
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}

        params = {'id': self.playlist_id}
        response = requests.get(url=url, params=params, headers=headers).content.decode()
        #print(response)
        return response

    def parse(self, response):
        song_id = []
        song_name = []

        tree = etree.HTML(response)

        title = tree.xpath('//title/text()')[0]
        title = re.findall(r'(.*?) - 歌单 - 网易云音乐', title)[0]
        print(title)
        song_id_long = tree.xpath('//ul[@class="f-hide"]/li/a/@href')
        for i in song_id_long:
            song_id.append((re.findall(r'id=(.+)', i))[0])

        song_name = tree.xpath('//ul[@class="f-hide"]//a/text()')

        print(len(song_id), song_id)
        print(len(song_name),song_name)
        return  title, song_id, song_name


    def run(self):

        response = self.spider()
        title, song_id_list, song_name = self.parse(response)
        return title, song_id_list, song_name



if __name__ == "__main__":
    playlist_id = input('网易云歌单id：')  #  6638111891  4900784000
    playlist_info = playlist(playlist_id)
    playlist_info.run()

    print('over!')